package com.ruicar.afs.cloud.apply.admin.manage.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.ruicar.afs.cloud.admin.service.SysUserService;
import com.ruicar.afs.cloud.apply.admin.auth.util.DataAccessUtil;
import com.ruicar.afs.cloud.apply.admin.manage.common.Constants;
import com.ruicar.afs.cloud.apply.admin.manage.condition.ApplyAdminDTO;
import com.ruicar.afs.cloud.apply.admin.manage.condition.ApplyUserCondition;
import com.ruicar.afs.cloud.apply.admin.manage.entity.*;
import com.ruicar.afs.cloud.apply.admin.manage.service.*;
import com.ruicar.afs.cloud.common.core.constant.CommonConstants;
import com.ruicar.afs.cloud.common.core.enums.AfsEnumUtil;
import com.ruicar.afs.cloud.common.core.exception.AfsBaseException;
import com.ruicar.afs.cloud.common.core.log.annotation.SysLog;
import com.ruicar.afs.cloud.common.core.query.QueryCondition;
import com.ruicar.afs.cloud.common.core.security.feign.Oauth2OperationService;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.modules.apply.dto.UserDTO;
import com.ruicar.afs.cloud.common.modules.apply.enums.CarTypeEnum;
import com.ruicar.afs.cloud.common.modules.apply.enums.CreatUserEnum;
import com.ruicar.afs.cloud.common.modules.apply.enums.RoleEnum;
import com.ruicar.afs.cloud.common.modules.apply.enums.StatusEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.security.core.userdetails.User;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @author xudongdong
 * @date 2020-06-03
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/applyUser")
@Api(value = "applyUser", description = "用户管理模块")
public class ApplyUserController {

    private final ApplyUserService userService;
    private final ApplyUserRoleService userRoleService;
    private final ApplyDepartmentService applyDepartmentService;
    private final ApplyUserAuthorizeService userAuthorizeService;
    private final ApplyUserAppertainService userAppertainService;
    private final ApplyRoleService applyRoleService;
    private final ApplyDeptAuthRegionService applyDeptAuthRegionService;
    private final SysUserPowerService sysUserPowerService;

    private final ApplyUserTempService applyUserTempService;
    private final ApplyUserRoleTempService applyUserRoleTempService;
    private final ComAttachementFileService comAttachementFileService;

    private final SysUserService sysUserService;
    @PostMapping("/getUserListData")
    @ApiOperation(value = "多条件分页获取用户列表")
    public IResponse<IPage<SysUser>> getUserListData(@RequestBody QueryCondition<ApplyUserCondition> user) {

        IPage<SysUser> userList = userService.page(new Page(user.getPageNumber(), user.getPageSize())
                , Wrappers.<SysUser>query().lambda()
                        .eq(DataAccessUtil.isAdmin(), SysUser::getChannelId, DataAccessUtil.getChannelId())
                        .eq(user.getCondition().getDeptId() != null, SysUser::getDeptId, user.getCondition().getDeptId())
                        .eq(StringUtils.isNotEmpty(user.getCondition().getLockFlag()), SysUser::getLockFlag, user.getCondition().getLockFlag())
                        .like(StringUtils.isNotEmpty(user.getCondition().getUserRealName()), SysUser::getUserRealName, user.getCondition().getUserRealName())
                        .like(StringUtils.isNotEmpty(user.getCondition().getSearchPhone()), SysUser::getPhone, user.getCondition().getSearchPhone())
                        .like(StringUtils.isNotEmpty(user.getCondition().getSearchEmail()), SysUser::getUserEmail, user.getCondition().getSearchEmail())
                        .ge(StringUtils.isNotEmpty(user.getCondition().getStartDate()), SysUser::getCreateTime, user.getCondition().getStartDate())
                        .le(StringUtils.isNotEmpty(user.getCondition().getEndDate()), SysUser::getCreateTime, user.getCondition().getEndDate()));
        for (SysUser u : userList.getRecords()) {
            Set<String> set = new HashSet<>();
            // 关联部门
            if (u.getDeptId() != null) {
                SysDepartment department = applyDepartmentService.getById(u.getDeptId());
                u.setDepartmentTitle(department.getTitle());
            }
            // 关联角色
            List<SysRole> newRolesList = userService.findRolesByUserId(u.getUserId(), CarTypeEnum.newCar);
            List<SysRole> oldRolesList = userService.findRolesByUserId(u.getUserId(), CarTypeEnum.oldCar);
            if (newRolesList.size() > 0) {
                for (int i = 0; i < newRolesList.size(); i++) {
                    set.add(newRolesList.get(i).getRoleName());
                }
            }
            if (oldRolesList.size() > 0) {
                for (int i = 0; i < oldRolesList.size(); i++) {
                    set.add(oldRolesList.get(i).getRoleName());
                }
            }

            u.setOldRoles(oldRolesList);
            u.setNewRoles(newRolesList);
            u.setPassword(null);
            u.setRoleName(StringUtils.strip(set.toString(), "[]"));

        }
        return IResponse.success(userList);
    }


    @PostMapping("/getUserListDataTemp")
    @ApiOperation(value = "多条件分页获取用户临时表表")
    public IResponse<IPage<SysUserTemp>> getUserListDataTemp(@RequestBody QueryCondition<ApplyUserCondition> user) {

        IPage<SysUserTemp> userList = applyUserTempService.page(new Page(user.getPageNumber(), user.getPageSize())
                , Wrappers.<SysUserTemp>query().lambda()
                        .eq(DataAccessUtil.isAdmin(), SysUserTemp::getChannelId, DataAccessUtil.getChannelId())
                        .eq(user.getCondition().getDeptId() != null, SysUserTemp::getDeptId, user.getCondition().getDeptId())
                        .eq(StringUtils.isNotEmpty(user.getCondition().getLockFlag()), SysUserTemp::getLockFlag, user.getCondition().getLockFlag())
                        .like(StringUtils.isNotEmpty(user.getCondition().getUserRealName()), SysUserTemp::getUserRealName, user.getCondition().getUserRealName())
                        .like(StringUtils.isNotEmpty(user.getCondition().getSearchPhone()), SysUserTemp::getPhone, user.getCondition().getSearchPhone())
                        .like(StringUtils.isNotEmpty(user.getCondition().getSearchEmail()), SysUserTemp::getUserEmail, user.getCondition().getSearchEmail())
                        .ge(StringUtils.isNotEmpty(user.getCondition().getStartDate()), SysUserTemp::getCreateTime, user.getCondition().getStartDate())
                        .le(StringUtils.isNotEmpty(user.getCondition().getEndDate()), SysUserTemp::getCreateTime, user.getCondition().getEndDate()));
        for (SysUserTemp u : userList.getRecords()) {
            Set<String> set = new HashSet<>();
            // 关联部门
            if (u.getDeptId() != null) {
                SysDepartment department = applyDepartmentService.getById(u.getDeptId());
                u.setDepartmentTitle(department.getTitle());
            }
            // 关联角色
            List<SysRole> newRolesList = userService.findRolesByUserIdTemp(u.getId(), CarTypeEnum.newCar);
            List<SysRole> oldRolesList = userService.findRolesByUserIdTemp(u.getId(), CarTypeEnum.oldCar);
            if (newRolesList.size() > 0) {
                for (int i = 0; i < newRolesList.size(); i++) {
                    set.add(newRolesList.get(i).getRoleName());
                }
            }
            if (oldRolesList.size() > 0) {
                for (int i = 0; i < oldRolesList.size(); i++) {
                    set.add(oldRolesList.get(i).getRoleName());
                }
            }

            u.setOldRoles(oldRolesList);
            u.setNewRoles(newRolesList);
            u.setPassword(null);
            u.setUserId(u.getId());
            u.setRoleName(StringUtils.strip(set.toString(), "[]"));

        }
        return IResponse.success(userList);
    }

    /**
     * @param userCondition
     * @return
     */
    @PostMapping("/editUser")
    @ApiOperation(value = "修改用户资料")
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(value = CommonConstants.USER_CACHE_KEY_PREFIX, allEntries = true)
    public IResponse<Boolean> edit(@RequestBody ApplyUserCondition userCondition) {
        userCondition.setChannelId(DataAccessUtil.getChannelId());
        //删除该用户角色
        userRoleService.remove(Wrappers.<SysUserRole>query().lambda().
                eq(SysUserRole::getUserId, userCondition.getUserId()));

        // 第一步先看看这条信息现在的状态
        SysUser old = userService.getOne(Wrappers.<SysUser>query().lambda().eq(SysUser::getUserId,userCondition.getUserId()));
        if (StatusEnum.YES.getValue().equals(old.getLockFlag())) {
            // 说明用户已经被停用了，此时应该先判断这个用户类型数量是不是没有超
            //校验用户数量
            userService.chackRole(userCondition);
        } else {
            //如果是修改的话。那么也要校验数量
            userService.chackRole(userCondition);
        }

        userCondition.setUsername(old.getUsername());
        userCondition.setPassword(old.getPassword());
        userCondition.setLockFlag(StatusEnum.NO.getValue());
        if (!userService.updateById(userCondition)) {
            return IResponse.fail("修改失败");
        }

        // 查询出来贷后的角色id
        SysRole loan = applyRoleService.getOne(Wrappers.<SysRole>query().lambda().eq(SysRole::getRoleCode, RoleEnum.ROLE_LOANAFTER.name()));
        // 查询佣金角色
        SysRole brokerage = applyRoleService.getOne(Wrappers.<SysRole>query().lambda().eq(SysRole::getRoleCode, RoleEnum.ROLE_COMMISSION.name()));

        // 查询进来的区域是新车的码
        List<SysDeptAuthRegion> newCarRegion = applyDeptAuthRegionService.list(Wrappers.<SysDeptAuthRegion>query().lambda()
                .eq(SysDeptAuthRegion::getDeptId, userCondition.getDeptId()).eq(SysDeptAuthRegion::getBusinessType, CarTypeEnum.newCar));
        if (newCarRegion.size() > 0) {
            if (userCondition.getNewRoleIds() != null && userCondition.getNewRoleIds().length > 0) {
                for (Long roleId : userCondition.getNewRoleIds()) {

                    // 如过角色id 是贷后或者佣金 也给二手车一个
                    if ((roleId.toString().equals(loan.getId().toString()))  || (roleId.toString().equals(brokerage.getId().toString())) ) {
                        userRoleService.remove(Wrappers.<SysUserRole>query().lambda().eq(SysUserRole::getUserId,userCondition.getUserId()).eq(SysUserRole::getRoleId,roleId));
                        SysUserRole us = new SysUserRole();
                        us.setUserId(userCondition.getUserId());
                        us.setRoleId(roleId);
                        us.setBusinessType(CarTypeEnum.oldCar);
                        userRoleService.save(us);
                    }
                    SysUserRole ur = new SysUserRole();
                    ur.setUserId(userCondition.getUserId());
                    ur.setRoleId(roleId);
                    ur.setBusinessType(CarTypeEnum.newCar);
                    userRoleService.save(ur);
                }
            }
        }
        List<SysDeptAuthRegion> oldCarRegion = applyDeptAuthRegionService.list(Wrappers.<SysDeptAuthRegion>query().lambda()
                .eq(SysDeptAuthRegion::getDeptId, userCondition.getDeptId()).eq(SysDeptAuthRegion::getBusinessType, CarTypeEnum.oldCar));
        if (oldCarRegion.size() > 0) {
            if (userCondition.getOldRoleIds() != null && userCondition.getOldRoleIds().length > 0) {
                for (Long roleId : userCondition.getOldRoleIds()) {
                    // 如过角色id 是贷后或者佣金 也给新车一个
                    if ((roleId.toString().equals(loan.getId().toString())) || (roleId.toString().equals(brokerage.getId().toString())) ) {
                        userRoleService.remove(Wrappers.<SysUserRole>query().lambda().eq(SysUserRole::getUserId,userCondition.getUserId()).eq(SysUserRole::getRoleId,roleId));
                        SysUserRole us = new SysUserRole();
                        us.setUserId(userCondition.getUserId());
                        us.setRoleId(roleId);
                        us.setBusinessType(CarTypeEnum.newCar);
                        userRoleService.save(us);
                    }
                    SysUserRole ur = new SysUserRole();
                    ur.setUserId(userCondition.getUserId());
                    ur.setRoleId(roleId);
                    ur.setBusinessType(CarTypeEnum.oldCar);
                    userRoleService.save(ur);
                }
            }
        }

        // 这边去修改权限的问题
        // 这边去判断用户的权限
        SysUserPower power=sysUserPowerService.getOne(Wrappers.<SysUserPower>query().lambda().eq(SysUserPower::getUserId,userCondition.getUserId()));
        if(power==null){
            power.setUserId(userCondition.getUserId());
            power.setChannelId(userCondition.getChannelId());
            if(userCondition.getNewRoleIds().length> 0){
                // 说明有新车
                power.setNewApplyPower(StatusEnum.NO.getValue());
                power.setNewAccountPower(StatusEnum.NO.getValue());
            }else {
                power.setNewApplyPower(StatusEnum.NOTHING.getValue());
                power.setNewAccountPower(StatusEnum.NOTHING.getValue());
            }
            if(userCondition.getOldRoleIds().length>0){
                // 说明有二手车
                power.setOdlApplyPower(StatusEnum.NO.getValue());
                power.setOldAccountPower(StatusEnum.NO.getValue());
            }else {
                power.setOdlApplyPower(StatusEnum.NOTHING.getValue());
                power.setOldAccountPower(StatusEnum.NOTHING.getValue());
            }
            power.setLockFlag(StatusEnum.NO.getValue());
            sysUserPowerService.save(power);
        }else {
            if(userCondition.getNewRoleIds().length> 0){
                // 说明有新车
                if(StatusEnum.NOTHING.getValue().toString().equals(power.getNewApplyPower())){
                    power.setNewApplyPower(StatusEnum.NO.getValue());
                }
                if(StatusEnum.NOTHING.getValue().toString().equals(power.getNewAccountPower())){
                    power.setNewAccountPower(StatusEnum.NO.getValue());
                }
            }else {
                power.setNewApplyPower(StatusEnum.NOTHING.getValue());
                power.setNewAccountPower(StatusEnum.NOTHING.getValue());
            }
            if(userCondition.getOldRoleIds().length>0){
                // 说明有二手车
                if(StatusEnum.NOTHING.getValue().toString().equals(power.getOdlApplyPower())){
                    power.setOdlApplyPower(StatusEnum.NO.getValue());
                }
                if(StatusEnum.NOTHING.getValue().toString().equals(power.getOldAccountPower())){
                    power.setOldAccountPower(StatusEnum.NO.getValue());
                }
            }else {
                power.setOdlApplyPower(StatusEnum.NOTHING.getValue());
                power.setOldAccountPower(StatusEnum.NOTHING.getValue());
            }
            sysUserPowerService.update(power,Wrappers.<SysUserPower>query().lambda().eq(SysUserPower::getUserId,userCondition.getUserId()));
        }
        return IResponse.success(Boolean.TRUE).setMsg("操作成功");
    }

    @PostMapping("/addUser")
    @ApiOperation(value = "添加用户")
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(value = CommonConstants.USER_CACHE_KEY_PREFIX, allEntries = true)
    public IResponse<Boolean> adduser(@RequestBody ApplyUserCondition userCondition) {
        userService.saveUser(userCondition);
        return IResponse.success(Boolean.TRUE).setMsg("操作成功");
    }

    @PostMapping("/addUserTemp")
    @ApiOperation(value = "添加临时表用户")
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(value = CommonConstants.USER_CACHE_KEY_PREFIX, allEntries = true)
    public IResponse<Boolean> addUserTemp(@RequestBody ApplyUserCondition userCondition) {
        return userService.saveUserTemp(userCondition);
    }

    @PostMapping("/editUserTemp")
    @ApiOperation(value = "修改用户资料")
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(value = CommonConstants.USER_CACHE_KEY_PREFIX, allEntries = true)
    public IResponse<Boolean> editUserTemp(@RequestBody ApplyUserCondition userCondition) {
        List<SysUser> userList = userService.list(Wrappers.<SysUser>query().lambda().eq(SysUser::getIdentityNumber, userCondition.getIdentityNumber()).eq(SysUser::getLockFlag, StatusEnum.NO.getValue().toString()).eq(SysUser::getDelFlag, StatusEnum.NO.getValue().toString()).notIn(SysUser::getChannelId, DataAccessUtil.getChannelId().toString()));
        if (userList.size() > 0) {
            throw new AfsBaseException(CommonConstants.FAIL, "此身份证号已在其他渠道使用！");
        }

        return userService.editUserTemp(userCondition);
    }

    @PostMapping("/disable/{id}")
    @ApiOperation(value = "禁用用户")
    @Transactional
    @SysLog("禁用用户")
    @CacheEvict(value = CommonConstants.USER_CACHE_KEY_PREFIX, allEntries = true)
    public IResponse<Boolean> disable(@PathVariable Long id) {
        SysUser user = userService.getOne(Wrappers.<SysUser>query().lambda().eq(SysUser::getUserId, id));
        if (user == null) {
            return IResponse.fail("通过userId获取用户失败");
        }
        user.setLockFlag(StatusEnum.YES.getValue());
        userService.updateById(user);
        return new IResponse().setData(true);
    }

    @RequestMapping(value = "/upAllByIds/{ids}", method = RequestMethod.DELETE)
    @ApiOperation(value = "批量通过ids禁用用户")
    @Transactional
    @SysLog("批量禁用用户")
    public IResponse<Boolean> upAllByIds(@PathVariable String[] ids) {
        for (int j = 0; j < Arrays.asList(ids).size(); j++) {
            Long id = Long.valueOf(Arrays.asList(ids).get(j));
            SysUser user = userService.getOne(Wrappers.<SysUser>query().lambda().eq(SysUser::getUserId, id));
            if (user == null) {
                throw new AfsBaseException("未找到相应用户停用失败！");
            }
            user.setLockFlag(StatusEnum.YES.getValue());
            userService.updateById(user);
            SysUserTemp tempUser =applyUserTempService.getOne(Wrappers.<SysUserTemp>query().lambda().eq(SysUserTemp::getId,id));
            if (tempUser == null) {
                throw new AfsBaseException("未找到相应用户停用失败！");
            }
            tempUser.setLockFlag(StatusEnum.YES.getValue());
            applyUserTempService.update(tempUser,Wrappers.<SysUserTemp>query().lambda().eq(SysUserTemp::getId,id));

            // 去权限做标识
            sysUserPowerService.update(Wrappers.<SysUserPower>lambdaUpdate().set(SysUserPower::getStopAccount,StatusEnum.YES.getValue()).eq(SysUserPower::getUserId,id));

        }
        return new IResponse<Boolean>().setMsg("批量通过id停用成功");
    }

    @RequestMapping(value = "/passWord/{id}", method = RequestMethod.DELETE)
    @ApiOperation(value = "根据id 重置密码")
    @SysLog("根据id 重置密码")
    public IResponse<Boolean> passWord(@PathVariable Long id) {
        SysUser user = userService.getOne(Wrappers.<SysUser>query().lambda().eq(SysUser::getUserId, id));
        if (user == null) {
            throw new AfsBaseException("未找到相应用户重置失败！");
        }
        user.setPassword(SysUserService.ENCODER.encode(AfsEnumUtil.key(CreatUserEnum.DEFAULT_PWD)));
        user.setLastPassChangeTime(0L);
        userService.updateById(user);
        com.ruicar.afs.cloud.admin.entity.SysUser tempUser = new com.ruicar.afs.cloud.admin.entity.SysUser();
        tempUser.setUsername(user.getUsername());
//        sysUserService.kickOutUser(tempUser);
        return new IResponse<Boolean>().setMsg("重置密码成功！");
    }

    @PostMapping("/enable/{id}")
    @ApiOperation(value = "后台启用用户")
    @Transactional
    @SysLog("启用用户")
    @CacheEvict(value = CommonConstants.USER_CACHE_KEY_PREFIX, allEntries = true)
    public IResponse<Object> enable(@PathVariable Long id) {
        userService.enableUser(id);
        return new IResponse().setData(true);
    }

    @RequestMapping(value = "/delByIds/{ids}", method = RequestMethod.DELETE)
    @ApiOperation(value = "批量通过ids删除")
    @Transactional
    @SysLog("批量通过ids删除")
    @CacheEvict(value = CommonConstants.USER_CACHE_KEY_PREFIX, allEntries = true)
    public IResponse<Boolean> delAllByIds(@PathVariable Long[] ids) {

        userService.removeByIds(Arrays.asList(ids));
        for (Long id : ids) {
            //删除关联角色
            userRoleService.remove(Wrappers.<SysUserRole>query().lambda().
                    eq(SysUserRole::getUserId, id));
            //删除该用户所属区域
            userAppertainService.remove(Wrappers.<SysUserAppertain>query().lambda().
                    eq(SysUserAppertain::getUserId, id));
            //删除该用户所属区域
            userAuthorizeService.remove(Wrappers.<SysUserAuthorize>query().lambda().
                    eq(SysUserAuthorize::getUserId, id));
        }
        return new IResponse<Boolean>().setMsg("批量通过id删除数据成功");
    }

    @GetMapping("/getAllSaleManByChannelId/{channelId}/{businessType}")
    @ApiOperation(value = "根据渠道id获取所有业务员")
    public IResponse getAllSaleManByChannelId(@PathVariable(value = "channelId") String channelId, @PathVariable(value = "businessType") String businessType) {

        List<SysUser> userList = userService.list(Wrappers.<SysUser>query().lambda()
                .eq(SysUser::getChannelId, channelId)
                .eq(SysUser::getLockFlag, StatusEnum.NO.getValue())
        );
        List<SysUser> users = new ArrayList<>();

        if (Constants.BUSINESS_TYPE_NEW_CAR.equals(businessType)) {
            for (SysUser u : userList) {
                List<SysRole> newRolesList = userService.findRolesByUserId(u.getUserId(), CarTypeEnum.newCar);
                u.setNewRoles(newRolesList);
                u.setPassword(null);
                for (SysRole roles : newRolesList) {
                    if (Constants.ROLE_XCRECORDED.equals(roles.getRoleCode()) || Constants.ROLE_XCAPPLY.equals(roles.getRoleCode())) {
                        users.add(u);
                        break;
                    }
                }
            }
        }

        if (Constants.BUSINESS_TYPE_OLD_CAR.equals(businessType)) {
            for (SysUser u : userList) {
                List<SysRole> oldRolesList = userService.findRolesByUserId(u.getUserId(), CarTypeEnum.oldCar);
                u.setOldRoles(oldRolesList);
                u.setPassword(null);
                for (SysRole roles : oldRolesList) {
                    if (Constants.ROLE_APPLY.equals(roles.getRoleCode()) || Constants.ROLE_RECORDED.equals(roles.getRoleCode())) {
                        users.add(u);
                        break;
                    }
                }
            }
        }
        return IResponse.success(users);
    }

    @GetMapping("/getUserRealNameByUsername{username}")
    @ApiOperation(value = "根据username获取用户真名")
    public IResponse getUserRealNameByUsername(@PathVariable(value = "username") String username) {
        List<SysUser> userList = userService.list(Wrappers.<SysUser>query().lambda()
                .eq(SysUser::getUsername, username)
        );
        return IResponse.success(userList.get(0).getUserRealName());
    }


    @PostMapping("/findUserInfoByDeptId")
    @ApiOperation(value = "根据部门id获取用户")
    public IResponse<List<UserDTO>> findUserInfoByDeptId(@RequestBody ApplyUserCondition user) {
        ArrayList<Long> ids = Lists.newArrayList();
        ids.add(user.getDeptId());
        applyDepartmentService.getDepartmentIds(ids, user.getDeptId());
        //根据roleId查用户
        List<Long> userIds = new ArrayList<>();
        if(user.getRoleId() != null){
            List<SysUserRole> userRoles = userRoleService.list(Wrappers.<SysUserRole>query().lambda().eq(SysUserRole::getRoleId, user.getRoleId()));
            if(userRoles.size() > 0){
                for (SysUserRole userRole : userRoles){
                    Long userId = userRole.getUserId();
                    userIds.add(userId);
                }
            }
        }
        //根据部门id查询用户
        IPage<SysUser> userList = userService.page(new Page(user.getPageNumber(), user.getPageSize())
                , Wrappers.<SysUser>query().lambda()
                        .in(SysUser::getDeptId, ids)
                        .in(userIds.size()>0,SysUser::getUserId,userIds)
                        .eq(StringUtils.isNotEmpty(user.getLockFlag()), SysUser::getLockFlag, user.getLockFlag())
                        .like(StringUtils.isNotEmpty(user.getUserRealName()), SysUser::getUserRealName, user.getUserRealName())
                        .like(StringUtils.isNotEmpty(user.getUsername()), SysUser::getUsername, user.getUsername())
                        .like(StringUtils.isNotEmpty(user.getSearchPhone()), SysUser::getPhone, user.getSearchPhone())
                        .like(StringUtils.isNotEmpty(user.getSearchEmail()), SysUser::getUserEmail, user.getSearchEmail()));

        for (SysUser u : userList.getRecords()) {
            // 关联部门
            if (u.getDeptId() != null) {
                SysDepartment department = applyDepartmentService.getById(u.getDeptId().toString());
                u.setDepartmentTitle(department.getTitle());
            }
            SysUserPower power=sysUserPowerService.getOne(Wrappers.<SysUserPower>query().lambda().eq(SysUserPower::getUserId,u.getUserId()));
            if(power==null){
                u.setNewApplyPower(StatusEnum.NO.getValue());
                u.setNewAccountPower(StatusEnum.NO.getValue());
                u.setOdlApplyPower(StatusEnum.NO.getValue());
                u.setOldAccountPower(StatusEnum.NO.getValue());
                u.setUserManage(StatusEnum.NO.getValue());
            }else {
                u.setNewApplyPower(power.getNewApplyPower());
                u.setNewAccountPower(power.getNewAccountPower());
                u.setOdlApplyPower(power.getOdlApplyPower());
                u.setOldAccountPower(power.getOldAccountPower());
                u.setUserManage(power.getUserManage());
            }

            //关联角色
            String roleName = "";
            List<SysRole> rolesList = userService.findRolesInfo(u.getUserId());
            for (int i = 0; i < rolesList.size(); i++) {
                if(i != rolesList.size() - 1){
                    roleName = roleName + rolesList.get(i).getRoleName()+",";
                }else {
                    //最后一个循环,不需要加 ","号
                    roleName = roleName + rolesList.get(i).getRoleName();
                }
            }
            u.setRoleName(roleName);
        }
        return IResponse.success(userList);
    }

    /**
     * 同部门和同角色的用户
     *
     * @param condition
     * @return
     */
    @ApiOperation("同部门和同角色的用户")
    @PostMapping("/getTransferUser")
    public IResponse getTransferUser(@ModelAttribute ApplyUserCondition condition) {
        // 查询这个部门下面的子部门id
        // 再查出来他自己的子集id 有哪些
        ArrayList<Long> region = new ArrayList<>();
        this.getRegionIds(region,condition.getDeptId());
        region.add(condition.getDeptId());
        List<Long> ids =new ArrayList<>();
        ids=region;
        if(ids.size()<=0){
            throw new AfsBaseException("获取本部门和下级部门失败！");
        }
        Assert.isTrue(StringUtils.isNotEmpty(condition.getBusinessType()),"业务类型不允许为空");
        List<SysUser> list = userService.getTransferUser(condition,ids);
        return IResponse.success(list);
    }

    private void getRegionIds(ArrayList<Long> region,  Long deptId) {
        //查询二级分类的对象
        List<SysDepartment> orgAuthorizeRegions = applyDepartmentService.list(Wrappers.<SysDepartment>query()
                .lambda().eq(SysDepartment::getParentId, deptId));

        //遍历二级分类的对象，把二级分类的id加入到要删除的集合中
        for (SysDepartment orgAuthorizeRegion : orgAuthorizeRegions) {
            SysDepartment deptAuthRegion = new SysDepartment();
            BeanUtils.copyProperties(orgAuthorizeRegion, deptAuthRegion);
            region.add(deptAuthRegion.getId());

            //把二级分类的每一个ID，查询它下面的子节点
            this.getRegionIds(region, deptAuthRegion.getId());
        }
    }

    /**
     * 通过用户查询渠道ID
     * @param condition
     * @return
     */
    @ApiOperation("通过用户查询渠道ID")
    @PostMapping("/getChannelIdByUsername")
    public IResponse getChannelIdByUsername(@RequestBody ApplyUserCondition condition){

        SysUser user = userService.getOne(Wrappers.<SysUser>query().lambda().eq(SysUser::getUsername, condition.getUsername()));
        return IResponse.success(user.getChannelId());
    }

    /**
     * 通过用户登录名查询用户信息
     * @param condition
     * @return
     */
    @ApiOperation("通过用户登录名查询用户信息")
    @PostMapping("/getUserInfoByUsername")
    public IResponse getUserInfoByUsername(@RequestBody ApplyUserCondition condition){

        SysUser user = userService.getOne(Wrappers.<SysUser>query().lambda().eq(SysUser::getUsername, condition.getUsername()));
        return IResponse.success(user);
    }

    /**
     * 通过用户id查询用户附件信息
     * @param condition
     * @return
     */
    @ApiOperation("通过用户id查询用户附件信息")
    @PostMapping("/getUserFileByUserId")
    public IResponse getUserFileByUserId(@RequestBody ApplyUserCondition condition){
        List<ComAttachementFile> comAttachmentFileList = comAttachementFileService.list(Wrappers.<ComAttachementFile>query().lambda()
                .eq(ComAttachementFile::getBusiNo, condition.getUsername()).orderByDesc(ComAttachementFile::getCreateTime));
        if(comAttachmentFileList !=null && comAttachmentFileList.size()>0){
            return IResponse.success(comAttachmentFileList.get(0));
        }else{
            return IResponse.fail("见证人身份证正面未上传！");
        }
    }

    @PostMapping("/toExamineUser")
    @ApiOperation(value = "通过id审核用户")
    @Transactional
    public IResponse toExamineUser(@RequestBody ApplyAdminDTO user) {
        // 查询出来贷后的角色id
        SysRole loan = applyRoleService.getOne(Wrappers.<SysRole>query().lambda().eq(SysRole::getRoleCode, RoleEnum.ROLE_LOANAFTER.name()));
        // 查询佣金角色
        SysRole brokerage = applyRoleService.getOne(Wrappers.<SysRole>query().lambda().eq(SysRole::getRoleCode, RoleEnum.ROLE_COMMISSION.name()));

        List<Long> onlyNewRole =userService.getNewRole();
        List<Long> onlyOldRole = userService.getOldRole();
        // 因此我要声明佣金贷后集合
        List<Long> loanAnd =new ArrayList<>();
        loanAnd.add(loan.getId());
        loanAnd.add(brokerage.getId());

        // 查询原有用户信息
        SysUser usFormer =userService.getOne(Wrappers.<SysUser>query().lambda().eq(SysUser::getUserId,user.getUserId()));
        // 现有用户信息
        SysUserTemp tempFormer=applyUserTempService.getOne(Wrappers.<SysUserTemp>query().lambda().eq(SysUserTemp::getId,user.getUserId()));
        // 看看是不是拒绝，如果是拒绝需要去修改部门数据
        if(StatusEnum.REFUSE.getValue().toString().equals(user.getStatus())){
            if(usFormer!=null){
                usFormer.setUserRealName(user.getFormerUserRealName());
//                usFormer.setDeptId(user.getFormerDeptId());
                usFormer.setUserEmail(user.getFormerUserEmail());
                usFormer.setPhone(user.getFormerPhone());
                userService.update(usFormer,Wrappers.<SysUser>query().lambda().eq(SysUser::getUserId,usFormer.getUserId()));

                tempFormer.setUserRealName(user.getFormerUserRealName());
//                tempFormer.setDeptId(user.getFormerDeptId());
                tempFormer.setUserEmail(user.getFormerUserEmail());
                tempFormer.setPhone(user.getFormerPhone());
                applyUserTempService.update(tempFormer,Wrappers.<SysUserTemp>query().lambda().eq(SysUserTemp::getId,user.getUserId()));

            }
        }else {
            if(usFormer!=null){
                usFormer.setUserRealName(user.getUserRealName());
                usFormer.setUserEmail(user.getUserEmail());
                usFormer.setPhone(user.getPhone());
                userService.update(usFormer,Wrappers.<SysUser>query().lambda().eq(SysUser::getUserId,usFormer.getUserId()));

                tempFormer.setUserRealName(user.getUserRealName());
                tempFormer.setUserEmail(user.getUserEmail());
                tempFormer.setPhone(user.getPhone());
                applyUserTempService.update(tempFormer,Wrappers.<SysUserTemp>query().lambda().eq(SysUserTemp::getId,user.getUserId()));

            }
        }

        // 查询原有用户信息
        SysUser us =userService.getOne(Wrappers.<SysUser>query().lambda().eq(SysUser::getUserId,user.getUserId()));
        // 现有用户信息
        SysUserTemp temp=applyUserTempService.getOne(Wrappers.<SysUserTemp>query().lambda().eq(SysUserTemp::getId,user.getUserId()));

        // 查看临时表部门是新车二手车属性
        // 获取这个部门能做新车还是二手车  还是都可以
        List<SysDeptAuthRegion> newCarRegion = applyDeptAuthRegionService.list(Wrappers.<SysDeptAuthRegion>query().lambda()
                .eq(SysDeptAuthRegion::getDeptId, temp.getDeptId()).eq(SysDeptAuthRegion::getBusinessType, CarTypeEnum.newCar));

        List<SysDeptAuthRegion> oldCarRegion = applyDeptAuthRegionService.list(Wrappers.<SysDeptAuthRegion>query().lambda()
                .eq(SysDeptAuthRegion::getDeptId, temp.getDeptId()).eq(SysDeptAuthRegion::getBusinessType, CarTypeEnum.oldCar));


        if(CommonConstants.STATUS_ERROR.equals(user.getSign())){
            // 说明一个同意二个都同意
            if(StatusEnum.PASS.getValue().toString().equals(user.getStatus())){

                temp.setNewStatus(user.getStatus());
                temp.setOldStatus(user.getStatus());
                temp.setLockFlag(StatusEnum.NO.getValue());
                applyUserTempService.update(temp,Wrappers.<SysUserTemp>query().lambda().eq(SysUserTemp::getId,user.getUserId()));
                applyUserTempService.update(Wrappers.<SysUserTemp>lambdaUpdate().set(SysUserTemp::getNewDataId,null).set(SysUserTemp::getOldDataId,null).eq(SysUserTemp::getId,temp.getId()));
                userService.addOrUpUser(user.getUserId(),user.getBusinessType(),user.getApplyUserRoleList(),user.getApplyUserRoleTempList(),loan,brokerage,loanAnd);
            }else if(StatusEnum.REFUSE.getValue().toString().equals(user.getStatus())){

                // 说明是拒绝
                temp.setNewStatus(user.getStatus());
                temp.setOldStatus(user.getStatus());
                temp.setNewDataId(user.getReason());
                temp.setOldDataId(user.getReason());
                // 下面是数据回显内容
                if(us!=null){
                    temp.setUserRealName(us.getUserRealName());
                    temp.setUserEmail(us.getUserEmail());
                    temp.setDeptId(us.getDeptId());
                    temp.setPhone(us.getPhone());
                }
                applyUserTempService.update(temp,Wrappers.<SysUserTemp>query().lambda().eq(SysUserTemp::getId,user.getUserId()));
                if(us!=null){
                    // 现在需要回显数据角色信息
                    applyUserRoleTempService.remove(Wrappers.<SysUserRoleTemp>query().lambda().eq(SysUserRoleTemp::getUserId,user.getUserId()));
                    List<SysUserRole> roleList=userRoleService.list(Wrappers.<SysUserRole>query().lambda().eq(SysUserRole::getUserId,user.getUserId()));
                    for(SysUserRole role :roleList){
                        SysUserRoleTemp roleTemp =new SysUserRoleTemp();
                        roleTemp.setUserId(role.getUserId());
                        roleTemp.setRoleId(role.getRoleId());
                        roleTemp.setBusinessType(role.getBusinessType());
                        applyUserRoleTempService.save(roleTemp);
                    }
                }

            }else {
                throw  new AfsBaseException("获取审核状态失败!");
            }
        }else {
            // 说明只同意一个  需要考虑第二个人的感受
            log.info("==================================比较的==================================》"+StatusEnum.PASS.getValue().toString());
            log.info("===================================传递过来的=================================》"+user.getStatus());
            System.out.println("看看数据："+user.getStatus());
            if(StatusEnum.PASS.getValue().toString().equals(user.getStatus())){
                log.info("==================================我的通过的==================================》");
                // 看看是新车还是二手车
                if(CarTypeEnum.newCar.toString().equals(user.getBusinessType())){
                    // 说明是新车
                    temp.setNewStatus(user.getStatus());
                    temp.setLockFlag(StatusEnum.NO.getValue());
                    applyUserTempService.update(temp,Wrappers.<SysUserTemp>query().lambda().eq(SysUserTemp::getId,user.getUserId()));
                    applyUserTempService.update(Wrappers.<SysUserTemp>lambdaUpdate().set(SysUserTemp::getNewDataId,null).eq(SysUserTemp::getId,temp.getId()));
                    userService.addOrUpUser(user.getUserId(),user.getBusinessType(),user.getApplyUserRoleList(),user.getApplyUserRoleTempList(),loan,brokerage,loanAnd);
                }else {
                    // 说明是二手车
                    temp.setOldStatus(user.getStatus());
                    temp.setLockFlag(StatusEnum.NO.getValue());
                    applyUserTempService.update(temp,Wrappers.<SysUserTemp>query().lambda().eq(SysUserTemp::getId,user.getUserId()));
                    applyUserTempService.update(Wrappers.<SysUserTemp>lambdaUpdate().set(SysUserTemp::getOldDataId,null).eq(SysUserTemp::getId,temp.getId()));
                    userService.addOrUpUser(user.getUserId(),user.getBusinessType(),user.getApplyUserRoleList(),user.getApplyUserRoleTempList(),loan,brokerage,loanAnd);
                }

            }else if(StatusEnum.REFUSE.getValue().toString().equals(user.getStatus())){
                log.info("==================================我是不通过的==================================》");
                if(CarTypeEnum.newCar.toString().equals(user.getBusinessType())){
                    temp.setNewStatus(StatusEnum.REFUSE.getValue().toString());
                    temp.setNewDataId(user.getReason());
                }else {
                    temp.setOldStatus(StatusEnum.REFUSE.getValue().toString());
                    temp.setOldDataId(user.getReason());
                }
                applyUserTempService.update(temp,Wrappers.<SysUserTemp>query().lambda().eq(SysUserTemp::getId,user.getUserId()));
                // 说明是拒绝

                    // 先看看这个 部门是不是双重属性
                    if(newCarRegion.size()>0&&oldCarRegion.size()>0){
                        if(us!=null){
                            // 先移除这个部门所有的角色还有佣金贷后
                            // 先移除所有的现有本类型的角色
                            applyUserRoleTempService.remove(Wrappers.<SysUserRoleTemp>query().lambda().eq(SysUserRoleTemp::getUserId,user.getUserId()).eq(SysUserRoleTemp::getBusinessType,user.getBusinessType()));
                            // 再移除佣金贷后
                            applyUserRoleTempService.remove(Wrappers.<SysUserRoleTemp>query().lambda().eq(SysUserRoleTemp::getUserId,user.getUserId()).in(SysUserRoleTemp::getRoleId,loanAnd));
                            // 再移除正式表角色的数据
                            userRoleService.remove(Wrappers.<SysUserRole>query().lambda().eq(SysUserRole::getUserId,user.getUserId()).eq(SysUserRole::getBusinessType,user.getBusinessType()));
                            // 再移除正式表佣金贷后
                            userRoleService.remove(Wrappers.<SysUserRole>query().lambda().eq(SysUserRole::getUserId,user.getUserId()).in(SysUserRole::getRoleId,loanAnd));

                            // 再看看需要数据回显嘛
                            if(user.getApplyUserRoleList()!=null){
                                //说明之前有数据需要数据回显
                                for(SysUserRole role:user.getApplyUserRoleList()){
                                    // 增加正式表的角色
                                    SysUserRole userRole =new SysUserRole();
                                    userRole.setRoleId(role.getRoleId());
                                    userRole.setBusinessType(role.getBusinessType());
                                    userRole.setUserId(role.getUserId());
                                    userRoleService.save(userRole);
                                    // 增加临时表的角色
                                    SysUserRoleTemp userRoleTemp =new SysUserRoleTemp();
                                    userRoleTemp.setRoleId(role.getRoleId());
                                    userRoleTemp.setBusinessType(role.getBusinessType());
                                    userRoleTemp.setUserId(role.getUserId());
                                    applyUserRoleTempService.save(userRoleTemp);
                                    // 判断有没有佣金贷后
                                    if(loan.getId().toString().equals(role.getRoleId().toString())||brokerage.getId().toString().equals(role.getRoleId().toString())){
                                        // 需要给佣金贷后追加双重属性
                                        SysUserRole tempTemp=new SysUserRole();
                                        if(CarTypeEnum.newCar.toString().equals(role.getBusinessType().toString())){
                                            tempTemp.setBusinessType(CarTypeEnum.oldCar);
                                        }else {
                                            tempTemp.setBusinessType(CarTypeEnum.newCar);
                                        }
                                        tempTemp.setUserId(role.getUserId());
                                        tempTemp.setRoleId(role.getRoleId());
                                        userRoleService.save(tempTemp);

                                        // 增加临时表的数据
                                        SysUserRoleTemp roleTemptemp=new SysUserRoleTemp();
                                        if(CarTypeEnum.newCar.toString().equals(role.getBusinessType().toString())){
                                            roleTemptemp.setBusinessType(CarTypeEnum.oldCar);
                                        }else {
                                            roleTemptemp.setBusinessType(CarTypeEnum.newCar);
                                        }
                                        roleTemptemp.setUserId(role.getUserId());
                                        roleTemptemp.setRoleId(role.getRoleId());
                                        applyUserRoleTempService.save(roleTemptemp);

                                    }

                                }
                            }
                            // 再看看这个用户还有角色吗
                            List<SysUserRole> userRoles=userRoleService.list(Wrappers.<SysUserRole>query().lambda().eq(SysUserRole::getUserId,user.getUserId()));
                            if(userRoles.size()<=0){
                                us.setLockFlag(StatusEnum.YES.getValue());
                                userService.update(us,Wrappers.<SysUser>query().lambda().eq(SysUser::getUserId,user.getUserId()));
                            }
                        }

                    }else {
                        // 说明是单重属性，那么直接还原原来的数据状态
                        // 现在需要回显数据角色信息
                        if(us!=null){
                            applyUserRoleTempService.remove(Wrappers.<SysUserRoleTemp>query().lambda().eq(SysUserRoleTemp::getUserId,user.getUserId()));
                            List<SysUserRole> roleList=userRoleService.list(Wrappers.<SysUserRole>query().lambda().eq(SysUserRole::getUserId,user.getUserId()));
                            for(SysUserRole role :roleList){
                                SysUserRoleTemp roleTemp =new SysUserRoleTemp();
                                roleTemp.setUserId(role.getUserId());
                                roleTemp.setRoleId(role.getRoleId());
                                roleTemp.setBusinessType(role.getBusinessType());
                                applyUserRoleTempService.save(roleTemp);
                            }
                        }

                    }

            }else {
                throw  new AfsBaseException("获取审核状态失败!");
            }
            //再看看这次申请是不是的账户之前是不是被：主动停用。见证人到期停用，黑名单停用
            SysUserPower ppp=sysUserPowerService.getOne(Wrappers.<SysUserPower>query().lambda().eq(SysUserPower::getUserId,user.getUserId()));
            if(ppp!=null){
                if(StatusEnum.YES.getValue().toString().equals(ppp.getStopAccount().toString())){
                    List<Long> newAllRole =userService.getNewRole();
                    List<Long> oldAllRole =userService.getOldRole();
                    // 需要把另类外一个属性的角色进行移除
                    if(StatusEnum.PASS.getValue().toString().equals(user.getStatus())){
                        if(CarTypeEnum.newCar.toString().equals(user.getBusinessType())){
                            // 说明是新车那么去二手车说有角色
                            userRoleService.remove(Wrappers.<SysUserRole>query().lambda().eq(SysUserRole::getUserId,user.getUserId()).in(SysUserRole::getRoleId,oldAllRole));
                            // 再去查看这个角色有没有二手车角色
                            List<SysUserRole> oldRole =userRoleService.list(Wrappers.<SysUserRole>query().lambda().eq(SysUserRole::getUserId,user.getUserId()).eq(SysUserRole::getBusinessType,CarTypeEnum.oldCar.toString()));
                            ppp.setOdlApplyPower(StatusEnum.NOTHING.getValue());
                            if(oldRole.size()<=0){
                                ppp.setOldAccountPower(StatusEnum.NOTHING.getValue());
                            }
                            ppp.setStopAccount(StatusEnum.NO.getValue());
                            sysUserPowerService.update(ppp,Wrappers.<SysUserPower>query().lambda().eq(SysUserPower::getUserId,user.getUserId()));
                        }else {
                            // 去移除新车的角色
                            userRoleService.remove(Wrappers.<SysUserRole>query().lambda().eq(SysUserRole::getUserId,user.getUserId()).in(SysUserRole::getRoleId,newAllRole));
                            // 再去查看这个角色有没有二手车角色
                            List<SysUserRole> oldRole =userRoleService.list(Wrappers.<SysUserRole>query().lambda().eq(SysUserRole::getUserId,user.getUserId()).eq(SysUserRole::getBusinessType,CarTypeEnum.newCar.toString()));
                            ppp.setNewApplyPower(StatusEnum.NOTHING.getValue());
                            if(oldRole.size()<=0){
                                ppp.setNewAccountPower(StatusEnum.NOTHING.getValue());
                            }
                            ppp.setStopAccount(StatusEnum.NO.getValue());
                            sysUserPowerService.update(ppp,Wrappers.<SysUserPower>query().lambda().eq(SysUserPower::getUserId,user.getUserId()));
                        }

                    }
                }
            }
        }
        //  最后去处理图片的问题
        SysUserTemp puUser =applyUserTempService.getOne(Wrappers.<SysUserTemp>query().lambda().eq(SysUserTemp::getId,user.getUserId()));
        if(StatusEnum.PASS.getValue().toString().equals(user.getStatus())){
            List<ComAttachementFile> oldFile=comAttachementFileService.list(Wrappers.<ComAttachementFile>query().lambda().eq(ComAttachementFile::getBusiNo,user.getUserId().toString()).eq(ComAttachementFile::getFileStatus,StatusEnum.DRAFT.getValue().toString()));
            if(oldFile.size()>0){
                comAttachementFileService.remove(Wrappers.<ComAttachementFile>query().lambda().eq(ComAttachementFile::getBusiNo,user.getUserId().toString()).eq(ComAttachementFile::getFileStatus,StatusEnum.STANDARD.getValue().toString()));
                // 再把最后一个变成通过
                List<ComAttachementFile> fileList=comAttachementFileService.list(Wrappers.<ComAttachementFile>query().lambda().eq(ComAttachementFile::getBusiNo,user.getUserId().toString()).orderByDesc(ComAttachementFile::getCreateTime));
                if(fileList.size()>0){
                    fileList.get(0).setFileStatus(StatusEnum.STANDARD.getValue());
                    comAttachementFileService.updateById(fileList.get(0));
                }
                // 再移除没用的数据
                comAttachementFileService.remove(Wrappers.<ComAttachementFile>query().lambda().eq(ComAttachementFile::getBusiNo,user.getUserId().toString()).eq(ComAttachementFile::getFileStatus,StatusEnum.DRAFT.getValue().toString()));
            }
        }else {
            // 说明是拒绝
            if(StatusEnum.APPROVE.getValue().toString().equals(puUser.getNewStatus())||StatusEnum.REEXAMINE.getValue().toString().equals(puUser.getNewStatus())||StatusEnum.APPROVE.getValue().toString().equals(puUser.getOldStatus())||StatusEnum.REEXAMINE.getValue().toString().equals(puUser.getOldStatus())){

            }else {
                List<ComAttachementFile> fileList=comAttachementFileService.list(Wrappers.<ComAttachementFile>query().lambda().eq(ComAttachementFile::getBusiNo,user.getUserId().toString()).eq(ComAttachementFile::getFileStatus,StatusEnum.STANDARD.getValue().toString()));
                if(fileList.size()>0){
                    comAttachementFileService.remove(Wrappers.<ComAttachementFile>query().lambda().eq(ComAttachementFile::getBusiNo,user.getUserId().toString()).eq(ComAttachementFile::getFileStatus,StatusEnum.DRAFT.getValue().toString()));
                }
            }
        }
        // 这个地方单独去处理用户的部门
        if(us!=null&&user.getDeptId()!=user.getFormerDeptId()&&StatusEnum.REFUSE.getValue().toString().equals(user.getStatus())){
            // 重新查询一下用户的信息
            SysUser userFormer =userService.getOne(Wrappers.<SysUser>query().lambda().eq(SysUser::getUserId,user.getUserId()));
            // 现有用户信息
            SysUserTemp tempUserFormer=applyUserTempService.getOne(Wrappers.<SysUserTemp>query().lambda().eq(SysUserTemp::getId,user.getUserId()));

            // 说明只有有账号，那么就需要去处理部门
            // 获取老部门的数据id
            //部门新车权限
            List<SysDeptAuthRegion> newThisDept=applyDeptAuthRegionService.list(Wrappers.<SysDeptAuthRegion>query().lambda().eq(SysDeptAuthRegion::getDeptId,user.getDeptId()).eq(SysDeptAuthRegion::getBusinessType,CarTypeEnum.newCar.toString()));
            // 部门二手车权限
            List<SysDeptAuthRegion> oldThisDept=applyDeptAuthRegionService.list(Wrappers.<SysDeptAuthRegion>query().lambda().eq(SysDeptAuthRegion::getDeptId,user.getDeptId()).eq(SysDeptAuthRegion::getBusinessType,CarTypeEnum.oldCar.toString()));
            // 再获取临时表部门的
            if(newThisDept.size()>0&&oldThisDept.size()>0){
                // 这种情况的时候还要看看
                List<SysDeptAuthRegion> newFormerDept=applyDeptAuthRegionService.list(Wrappers.<SysDeptAuthRegion>query().lambda().eq(SysDeptAuthRegion::getDeptId,user.getFormerDeptId()).eq(SysDeptAuthRegion::getBusinessType,CarTypeEnum.newCar.toString()));
                // 部门二手车权限
                List<SysDeptAuthRegion> oldFormerDept=applyDeptAuthRegionService.list(Wrappers.<SysDeptAuthRegion>query().lambda().eq(SysDeptAuthRegion::getDeptId,user.getFormerDeptId()).eq(SysDeptAuthRegion::getBusinessType,CarTypeEnum.oldCar.toString()));
                if(newFormerDept.size()>0&&oldFormerDept.size()>0){
                    userFormer.setDeptId(user.getFormerDeptId());
                    userService.update(userFormer,Wrappers.<SysUser>query().lambda().eq(SysUser::getUserId,usFormer.getUserId()));

                    tempUserFormer.setDeptId(user.getFormerDeptId());
                    applyUserTempService.update(tempUserFormer,Wrappers.<SysUserTemp>query().lambda().eq(SysUserTemp::getId,user.getUserId()));
                }else {
                    // 这种情况需要看看新车或者二手车的进件权限
                    // 新车账号权限
                    List<SysUserRoleTemp> newUser =applyUserRoleTempService.list(Wrappers.<SysUserRoleTemp>query().lambda().eq(SysUserRoleTemp::getUserId,user.getUserId()).eq(SysUserRoleTemp::getBusinessType,CarTypeEnum.newCar.toString()).notIn(SysUserRoleTemp::getRoleId,loanAnd));
                    // 二手车账号权限
                    List<SysUserRoleTemp> oldUser =applyUserRoleTempService.list(Wrappers.<SysUserRoleTemp>query().lambda().eq(SysUserRoleTemp::getUserId,user.getUserId()).eq(SysUserRoleTemp::getBusinessType,CarTypeEnum.oldCar.toString()).notIn(SysUserRoleTemp::getRoleId,loanAnd));
                    if(newUser.size()>0&&oldUser.size()>0){
                        // 都大于0的时候不要去更换
                    }else {
                        userFormer.setDeptId(user.getFormerDeptId());
                        userService.update(userFormer,Wrappers.<SysUser>query().lambda().eq(SysUser::getUserId,usFormer.getUserId()));

                        tempUserFormer.setDeptId(user.getFormerDeptId());
                        applyUserTempService.update(tempUserFormer,Wrappers.<SysUserTemp>query().lambda().eq(SysUserTemp::getId,user.getUserId()));
                    }

                }
            }else {
                userFormer.setDeptId(user.getFormerDeptId());
                userService.update(userFormer,Wrappers.<SysUser>query().lambda().eq(SysUser::getUserId,usFormer.getUserId()));

                tempUserFormer.setDeptId(user.getFormerDeptId());
                applyUserTempService.update(tempUserFormer,Wrappers.<SysUserTemp>query().lambda().eq(SysUserTemp::getId,user.getUserId()));
            }
        }

        SysUserTemp newUserTemp =applyUserTempService.getOne(Wrappers.<SysUserTemp>query().lambda().eq(SysUserTemp::getId,user.getUserId()));
        // 重新判断
        // 重新刷新用户状态
        if(StatusEnum.APPROVE.getValue().toString().equals(newUserTemp.getNewStatus())||StatusEnum.REEXAMINE.getValue().toString().equals(newUserTemp.getNewStatus())||StatusEnum.APPROVE.getValue().toString().equals(newUserTemp.getOldStatus())||StatusEnum.REEXAMINE.getValue().toString().equals(newUserTemp.getOldStatus())){

        }else {
            // 需要重新判断下角色的过程
            // 新车账号权限
            List<SysUserRoleTemp> newUser =applyUserRoleTempService.list(Wrappers.<SysUserRoleTemp>query().lambda().eq(SysUserRoleTemp::getUserId,newUserTemp.getId()).eq(SysUserRoleTemp::getBusinessType,CarTypeEnum.newCar.toString()));
            // 二手车账号权限
            List<SysUserRoleTemp> oldUser =applyUserRoleTempService.list(Wrappers.<SysUserRoleTemp>query().lambda().eq(SysUserRoleTemp::getUserId,newUserTemp.getId()).eq(SysUserRoleTemp::getBusinessType,CarTypeEnum.oldCar.toString()));

            //部门新车权限
            List<SysDeptAuthRegion> newDept=applyDeptAuthRegionService.list(Wrappers.<SysDeptAuthRegion>query().lambda().eq(SysDeptAuthRegion::getDeptId,newUserTemp.getDeptId()).eq(SysDeptAuthRegion::getBusinessType,CarTypeEnum.newCar.toString()));
            // 部门二手车权限
            List<SysDeptAuthRegion> oldDept=applyDeptAuthRegionService.list(Wrappers.<SysDeptAuthRegion>query().lambda().eq(SysDeptAuthRegion::getDeptId,newUserTemp.getDeptId()).eq(SysDeptAuthRegion::getBusinessType,CarTypeEnum.oldCar.toString()));
            if(newDept.size()>=0){
                // 说明部门有新车，判断用户有新车吗
                if(newUser.size()<=0){
                    userRoleService.remove(Wrappers.<SysUserRole>query().lambda().eq(SysUserRole::getUserId,newUserTemp.getId()).in(SysUserRole::getRoleId,onlyNewRole));
                    applyUserTempService.update(Wrappers.<SysUserTemp>lambdaUpdate().set(SysUserTemp::getNewStatus,null).eq(SysUserTemp::getId,newUserTemp.getId()));
                }
            }else {
                userRoleService.remove(Wrappers.<SysUserRole>query().lambda().eq(SysUserRole::getUserId,newUserTemp.getId()).in(SysUserRole::getRoleId,onlyNewRole));
                applyUserTempService.update(Wrappers.<SysUserTemp>lambdaUpdate().set(SysUserTemp::getNewStatus,null).eq(SysUserTemp::getId,newUserTemp.getId()));
            }
            if(oldDept.size()>0){
                if(oldUser.size()<=0){
                    userRoleService.remove(Wrappers.<SysUserRole>query().lambda().eq(SysUserRole::getUserId,newUserTemp.getId()).in(SysUserRole::getRoleId,onlyOldRole));
                    applyUserTempService.update(Wrappers.<SysUserTemp>lambdaUpdate().set(SysUserTemp::getOldStatus,null).eq(SysUserTemp::getId,newUserTemp.getId()));
                }
            }else {
                userRoleService.remove(Wrappers.<SysUserRole>query().lambda().eq(SysUserRole::getUserId,newUserTemp.getId()).in(SysUserRole::getRoleId,onlyOldRole));
                applyUserTempService.update(Wrappers.<SysUserTemp>lambdaUpdate().set(SysUserTemp::getOldStatus,null).eq(SysUserTemp::getId,newUserTemp.getId()));
            }
        }





        return new IResponse<Boolean>().setMsg("操作完成！");
    }


    @GetMapping("/getAllSaleMenByChannelId/{channelId}")
    @ApiOperation(value = "根据渠道id获取所有业务员")
    public IResponse getAllSaleMenByChannelId(@PathVariable(value = "channelId") String channelId) {

        List<SysUser> userList = userService.list(Wrappers.<SysUser>query().lambda()
                .eq(SysUser::getChannelId, channelId)
        );
        List<SysUser> users = new ArrayList<>();
        for (SysUser u : userList) {
            List<SysRole> newRolesList = userService.findRolesByUserId(u.getUserId(), CarTypeEnum.newCar);
            List<SysRole> oldRolesList = userService.findRolesByUserId(u.getUserId(), CarTypeEnum.oldCar);
            u.setNewRoles(newRolesList);
            u.setOldRoles(oldRolesList);
            u.setPassword(null);
            int size = users.size();
            for (SysRole roles : newRolesList) {
                if (Constants.ROLE_XCRECORDED.equals(roles.getRoleCode()) || Constants.ROLE_XCAPPLY.equals(roles.getRoleCode())) {
                    users.add(u);
                    break;
                }
            }
            if(size == users.size()){
                for (SysRole roles : oldRolesList) {
                    if (Constants.ROLE_APPLY.equals(roles.getRoleCode()) || Constants.ROLE_RECORDED.equals(roles.getRoleCode())) {
                        users.add(u);
                        break;
                    }
                }
            }
        }
        return IResponse.success(users);
    }

    @PostMapping("/getUserById")
    @ApiOperation(value = "通过用户id 查询用户信息")
    public JSONObject  getUserById(@RequestBody JSONObject json) {
        Long id =json.getLong("dataId");
        JSONObject jsonObject = new JSONObject();
        if(id==null){
            jsonObject.put("success",0);
            jsonObject.put("message","获取用户信息失败");
            jsonObject.put("code","获取用户信息失败");
        }else{
            jsonObject.put("success",1);
            SysUser user =userService.getOne(Wrappers.<SysUser>query().lambda().eq(SysUser::getUserId,id));
            JSONObject data = new JSONObject();
            data.put("Wowuserid",user.getUserId());//用户ID
            data.put("Orgid",user.getChannelId());//经销商ID
            data.put("Name",user.getUserRealName());//用户名
            jsonObject.put("data",data);
        }
        return jsonObject;
    }

}
